import { pathToBase64, base64ToPath }  from '../../../js_sdk/mmmm-image-tools/index.js'//图片链接转base64工具
import{http} from '../requestAddress/rtas.js'
//上传图片,imgUrlList图片链接,name:图片上传文件夹
export async function uploadImgToOss(imgUrlList,name){
	var urlList = "" //保存上传成功返回的图片链接
	for(var i = 0; i< imgUrlList.length;i++){
		//截取图片名称
		var start = imgUrlList[i].lastIndexOf("/")
		var imgname = name + "/" +imgUrlList[i].substring(start+1)
		//转base64
		var base = await tobase64(imgUrlList[i])
		var url = await request(base,imgname) 
		if(i == imgUrlList.length-1 ){
			urlList += url 
		}else{
			urlList += url + ","
		}
	}
	return urlList
}
//删除图片
export function deleteImg(imgpath){
	var promise = new Promise(function(resolve,reject){
		uni.request({
			url:http+"/alyapi?delepath="+imgpath,
			method:"DELETE",
			complete: (res)=> {
				if(res.data.code == 20031){
					uni.$u.toast("删除成功")
					resolve("1")
				}else{
					uni.$u.toast("删除失败！")
					reject("0")
				}
			}
		})
	})
	return promise.then(res =>{
		return res
	}).catch(err =>{
		return err
	})
}
//转换base64原来个工具无法直接返回数据
function tobase64(url){
	return new Promise((resolve,reject)=>{
				pathToBase64(url).then(base64 => {
					resolve(base64)
				 }).catch(error => {
					console.error(error)
					reject(error)
				})		
		})		
}
//上传请求
function request(base,imgname){
		var promise = new Promise(function(resolve,reject){
			//封装传递对象
			var aly = {
				base64: base,
				name: imgname
			}
			//传后端
			uni.request({
				url: http+"/alyapi/uploadimg",
				data:aly,
				method:"POST",
				complete: (res) => {
					if(res.data.code == 20011){
						resolve(res.data.date)
					}else{
						reject(res.data)
					}
				}
			})
		})
		
		return promise.then(res=>{
			return res
		}).catch(err=>{
			return err
		})
}